//
//  HexMapLayer.cpp
//  DiceWar
//
//  Created by xiaofeng on 25/6/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#include "HexMapLayer.h"
#include "GameMaster.h"

USING_NS_CC;

namespace  
{
    const int kMapGridDepth = 0;
}

bool HexMapLayer::init()
{
    if (!CCLayer::init()) return false;
    
    createHexMapGridLayers();
    m_pCurrentPlayerSprite = NULL;
    
    return true;
}

void HexMapLayer::createHexMapGridLayers()
{
    for (MatrixIter iter = m_mapView.begin(); iter != m_mapView.end(); ++iter)
    {
        HexMapGridLayer* pView = HexMapGridLayer::node();
        this->addChild(pView, kMapGridDepth);
        *iter = pView;
    }
}

HexMapGridLayer* HexMapLayer::getGridView(int xIndex, int yIndex)
{
    return m_mapView(xIndex, yIndex);
}

void HexMapLayer::setGridView(int xIndex, int yIndex, HexMapGridLayer* pSprite)
{
    CCAssert(pSprite, "The sprite added should not be NULL");
    
    HexMapGridLayer* pGridView = m_mapView(xIndex, yIndex);
    if (pGridView) pGridView->release();
    
    m_mapView.setValue(xIndex, yIndex, pSprite);
    pSprite->retain();
}

void HexMapLayer::updateMapView()
{
    for (int xIndex = 0; xIndex < gameConstants::kHexMapSizeX; xIndex++)
        for (int yIndex = 0; yIndex < gameConstants::kHexMapSizeY; yIndex++)
            updateMapViewForGrid(xIndex, yIndex);
}

void HexMapLayer::updateMapViewForGrid(int coordinateX, int coordinateY)
{
    const HexMap& gameMap = GameMaster::instance().getHexMap();
    const HexMapGrid& kMapGrid = gameMap.getMapGrid(coordinateX, coordinateY);
    HexMapGridLayer* pMapGridView  = getGridView(coordinateX, coordinateY);
    pMapGridView->setDisplay(kMapGrid);
}